<template>
  <div>
    <div id="container0" class="btn0"></div>
  </div>
</template>
<script>
import AMap from "AMap";
//引入api
import { postGetLongitude } from "@/api/copyingMap";
//引入图片
//我的位置
import mineimage from "./images/mine.png";
//已抄水表标值
import yichao from "./images/yi-chao.png";
//未抄
import weichao from "./images/weichao.png";
//引入一张全透明的照片
import white from "./images/white.png";
export default {
  data() {
    return {
      msg: {
        title: "", //定位成功
        longitude: undefined, //当前经度
        latitude: undefined, //当前纬度
        state: "", //定位类别
        excursion: false, //是否经过偏移
        precision: undefined, //导航精度
        remark: "", //由于众多浏览器已不再支持非安全域的定位请求，为保位成功率和精度，请升级您的站点到HTTPS。
      },
      markers: [
        // {
        //   icon:
        //     "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-1.png",
        //   position: [116.205467, 39.907761],
        // },
      ],
    };
  },
  mounted() {},
  methods: {
    //用当前的手册id去查地图上水表的坐标点
    showLAL(CodeID) {
      //console.log(CodeID)
       postGetLongitude(CodeID).then((Response) => {
        let rends = Response.data;
        //存入以搜索的坐标点
        sessionStorage.setItem('copyPath',JSON.stringify(rends));
        this.markers = [];
        rends.forEach((element) => {
          if (element["jingDu"] && element["weiDu"]) {
            let obj = {
              position: [element["jingDu"] * 1, element["weiDu"] * 1],
              icon: element["cbStatus"] == "3" ? weichao : yichao,
              bookName: element["bookName"],
              cbStatus: element["cbStatus"],
              hangbookCode: element["hangbookCode"],
              watermeterNo: element["watermeterNo"],
            };
            this.markers.push(obj);
          }
        });
        //描点
        let that = this;
        var map = new AMap.Map("container0", {
          resizeEnable: true,
          center: [that.msg.longitude, that.msg.latitude],
          zoom: 10,
        });
        this.markers.forEach(function (marker) {
          new AMap.Marker({
            map: map,
            //icon: marker.icon,
            // icon: new AMap.Icon({
            //   image: marker.icon,
            //   size: new AMap.Size(26, 26), //图标大小
            //   imageSize: new AMap.Size(26, 26),
            // }),
            position: [marker.position[0], marker.position[1]],
            offset: new AMap.Pixel(-13, -17),
          });
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 10000, //超过10秒后停止定位，默认：5s
            position: "RB", //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition(function (status, result) {
            if (status == "complete") {
              onComplete(result);
            } else {
              onError(result);
            }
          });
          //解析定位结果
          function onComplete(data) {
            that.msg.title = "定位成功";
            that.msg.excursion = data.isConverted;
            that.msg.longitude = data.position.lng;
            that.msg.latitude = data.position.lat;
            that.msg.state = data.location_type;
            that.msg.precision = data.accuracy;
            that.msg.remark =
              "由于众多浏览器已不再支持非安全域的定位请求，为保位成功率和精度，请升级您的站点到HTTPS。";
              //存到session
              sessionStorage.setItem('longitude',data.position.lng)
              sessionStorage.setItem('latitude',data.position.lat)
          }
        });
        // map.getCenter()
        console.log(that.markers);
         //路线规划
        var driving = new AMap.Driving({
          // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式,还有其他几种方式见Api文档
          policy: AMap.DrivingPolicy.LEAST_TIME,
        });
        //把自己的坐标加到第一位
        let mlo={
            position: [that.msg.longitude, that.msg.latitude],
              icon: white,
              bookName: "自己的位置",
              cbStatus: 100,
              hangbookCode: '',
              watermeterNo: '',
        }
         that.markers.unshift(mlo);
        console.log(mlo)
        for (let i = 0; i < that.markers.length; i++) {
          if (1 < that.markers.length - 1) {
            console.log(i);
            console.log(i + 1);
            var start_xy = new AMap.LngLat(that.markers[i].position[0], that.markers[i].position[1]); // 起点的经纬度
            var end_xy = new AMap.LngLat(that.markers[i+1].position[0], that.markers[i+1].position[1]); // 终点的经纬度
            driving.search(start_xy, end_xy, function (status, result) {
          if (status === "complete") {
            if (result.routes && result.routes.length) {
              // 绘制第一条路线，也可以按需求绘制其它几条路线
              var path = that.parseRouteToPath(result.routes[0]);

              var startMarker = new AMap.Marker({
                position: path[0],
                icon: white,
                map: map,
              });

              var endMarker = new AMap.Marker({
                position: path[path.length - 1],
                icon: white,
                map: map,
              });

              var routeLine = new AMap.Polyline({
                path: path,
                isOutline: true,
                outlineColor: "#ffeeee",
                borderWeight: 2,
                strokeWeight: 5,
                strokeColor: "#0B99C3",
                lineJoin: "round",
              });

              routeLine.setMap(map);

              // 调整视野达到最佳显示区域
              map.setFitView([startMarker, endMarker, routeLine]);
              console.log("绘制驾车路线完成");
            }
          } else {
            console.log("获取驾车数据失败：" + result);
          }
        });
          }
        }
       

        
        console.log(this.markers);
      });
    },
    //加载地图
    loadingCopyingMap() {
      let that = this;
      var map = new AMap.Map("container0", {
        resizeEnable: true,
      });
      AMap.plugin("AMap.Geolocation", function () {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 10000, //超过10秒后停止定位，默认：5s
          position: "RB", //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function (status, result) {
          if (status == "complete") {
            onComplete(result);
          } else {
            onError(result);
          }
        });
      });
      //解析定位结果
      function onComplete(data) {
        that.msg.title = "定位成功";
        (that.msg["icons"] = new AMap.Icon({
          image: mineimage,
          size: new AMap.Size(52, 52), //图标大小
          imageSize: new AMap.Size(26, 26),
        })),
          (that.msg.excursion = data.isConverted);
        that.msg.longitude = data.position.lng;
        that.msg.latitude = data.position.lat;
        that.msg.state = data.location_type;
        that.msg.precision = data.accuracy;
        that.msg.remark =
          "由于众多浏览器已不再支持非安全域的定位请求，为保位成功率和精度，请升级您的站点到HTTPS。";
        that.Message(); //弹窗
      }
      //解析定位错误信息
      function onError(data) {}
    },
    //提示弹窗
    Message() {
      let msgs = `定位成功...当前经度:${this.msg.longitude},纬度:${this.msg.latitude},定位类别:${this.msg.state},是否经过偏移:${this.msg.excursion},消息:${this.msg.remark}`;
      this.$message({
        message: msgs,
        type: "success",
      });
    },
    parseRouteToPath(route) {
      var path = [];

      for (var i = 0, l = route.steps.length; i < l; i++) {
        var step = route.steps[i];

        for (var j = 0, n = step.path.length; j < n; j++) {
          path.push(step.path[j]);
        }
      }

      return path;
    },
  },
};
</script>
<style lang="scss" scoped>
.btn0 {
  width: 96%;
  margin-left: 30px;
  height: 470px;
}
</style>